var globalOptions = require('./globalOptions');
var GlobalErrorListener = function (e) {
    this.empty = true;
    this._type = e;
    this._arr = [];
    this._index = 0;
};
GlobalErrorListener.create = function (e) {
    return new GlobalErrorListener(e);
};
GlobalErrorListener.prototype.add = function (e) {
    var t = this._index++;
    this._arr.push({
        id: t,
        func: e
    });
    this.empty = false;
    return t;
};
GlobalErrorListener.prototype.remove = function (e) {
    var t = this._arr;
    var i = 0;
    if ('function' == typeof e)
        for (i = 0; i < t.length; i++) {
            var n = t[i].func;
            if (n === e) {
                t.splice(i, 1);
                this.empty = !t.length;
                return n;
            }
        }
    else
        for (i = 0; i < t.length; i++)
            if (t[i].id === e) {
                var a = t[i].func;
                t.splice(i, 1);
                this.empty = !t.length;
                return a;
            }
    return null;
};
GlobalErrorListener.prototype.call = function (e, t, i) {
    var n = this._arr;
    var a = false;
    for (var o = 0; o < n.length; o++) {
        false === r(this._type, n[o].func, e, t, i) && (a = true);
    }
    if (a)
        return false;
};
var r = GlobalErrorListener.safeCallback = function (e, t, i, a, r) {
    try {
        return t.apply(i, a);
    } catch (l) {
        var s = '[Exparser] [Error] [Component] ' + (e || 'Error Listener') + ' Error @ ';
        i && i.is && (s += i.is);
        s += '#' + (t.name || '(anonymous)');
        r && r.triggerLifeTime('error', [l]);
        (function (e, t) {
            if (!t.type || false !== o.call(null, [
                    e,
                    t
                ])) {
                if (globalOptions.throwGlobalError)
                    throw e;
                console.error(e.stack);
            }
        }(l, {
            message: s,
            type: e,
            element: i,
            method: t,
            args: a
        }));
    }
};
var o = GlobalErrorListener.create();
GlobalErrorListener.addGlobalErrorListener = function (e) {
    return o.add(e);
};
GlobalErrorListener.removeGlobalErrorListener = function (e) {
    return o.remove(e);
};
var s = null;
GlobalErrorListener.addGlobalWarningListener = function (e) {
    return (s = GlobalErrorListener.create()).add(e);
};
GlobalErrorListener.removeGlobalWarningListener = function (e) {
    if (s) {
        var t = s.remove(e);
        s.empty && (s = null);
        return t;
    }
    return null;
};
GlobalErrorListener.hasGlobalWarningListeners = function () {
    return !!s;
};
GlobalErrorListener.triggerWarning = function (e) {
    var t = '[Exparser] [Warning] [Component] ' + e;
    s.call(null, [t], null);
};
module.exports = GlobalErrorListener;
